package net.koodar.forge.system.menu.manager;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.koodar.forge.system.menu.model.entity.Menu;
import net.koodar.forge.system.role.model.entity.RoleMenu;
import net.koodar.forge.system.menu.model.enums.MenuTypeEnum;
import net.koodar.forge.system.menu.dao.MenuMapper;
import net.koodar.forge.system.role.manager.RoleMenuManager;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyc
 */
@Service
@RequiredArgsConstructor
public class MenuManager extends ServiceImpl<MenuMapper, Menu> {

	private final RoleMenuManager roleMenuManager;

	public List<Menu> listMenuRoute() {
		return baseMapper.selectList(Wrappers.<Menu>lambdaQuery().in(Menu::getType, List.of(MenuTypeEnum.MENU.getValue(), MenuTypeEnum.CHILD_MENU.getValue())));
	}

	public List<Menu> listPermissionByRoleIds(Collection<Long> roleIds) {
		List<RoleMenu> roleMenus = roleMenuManager.findListByRoleIdIn(roleIds);
		List<Long> menuIds = roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
		return baseMapper.selectBatchIds(menuIds);
	}

	public List<Menu> listMenuPermissionByRoleIds(Collection<Long> roleIds) {
		List<Menu> menus = this.listPermissionByRoleIds(roleIds);
		return menus.stream()
				.filter(permission -> !permission.getType()
						.equals(MenuTypeEnum.PERMISSIONS.getValue()))
				.collect(Collectors.toList());
	}

	public List<Menu> listByName(Collection<String> names) {
		return baseMapper.selectList(Wrappers.<Menu>lambdaQuery().in(Menu::getName, names));
	}

	public Menu findByName(String name) {
		List<Menu> menus = baseMapper.selectList(Wrappers.<Menu>lambdaQuery().eq(Menu::getName, name));
		return menus.isEmpty() ? null : menus.get(0);
	}

	public List<Menu> findByRoleId(Long roleId) {
		return baseMapper.findByRoleId(roleId);
	}
}
